<?php

namespace app\admin\controller\xmwms\purchase;

use app\common\controller\Backend;
use app\common\library\SnowFlake;
use app\service\PurchaseService;
use \app\admin\model\xmwms\purchase\Detail;
use think\facade\Db;
use Throwable;

/**
 * 采购订单管理
 */
class Order extends Backend
{
     /**
      * Order模型对象
      * @var object
      * @phpstan-var \app\admin\model\xmwms\purchase\Order
      */
     protected object $model;

     protected array|string $preExcludeFields = ['id', 'create_time', 'update_time'];

     protected string|array $quickSearchField = ['id'];
     //关联查询
     protected array $withJoinTable = ['detail'];

     public function initialize(): void
     {
          parent::initialize();
          $this->model = new \app\admin\model\xmwms\purchase\Order;
     }


     /**
      * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
      */

     //采购订单列表
     public function index(): void
     {
          if ($this->request->param('select')) {
               $this->select();
          }

          list($where, $alias, $limit, $order) = $this->queryBuilder();
          $requestParams = $this->request->param();
          $res = $this->model
               ->field($this->indexField)
               ->withJoin($this->withJoinTable, $this->withJoinType)
               ->alias($alias)
               ->where($where);
          //判断他的角色如果是管理就看所有 如果是采购员就看到他自己提交的
          $admin_id = $this->auth->id;
          $admin = Db::name('admin_group_access')->where('uid', $admin_id)->find();
          if ($admin['group_id'] != 1) {
               $res->where('admin_id', '=', $admin_id);
          }
          if (!empty($requestParams['admin_id'])) {
               $res->where('admin_id', '=', $requestParams['admin_id']);
          }
          if (!empty($requestParams['platform'])) {
               $res->where('platform', '=', $requestParams['platform']);
          } else {
               $res->where('platform', '=', 1);
          }
          if (!empty($requestParams['start_time']) && !empty($requestParams['end_time'])) {
               //时间区间查询
               $res->whereBetweenTime('create_time', $requestParams['start_time'], $requestParams['end_time']);
          }
          if (!empty($requestParams['purchase_no'])) {
               $res->where('purchase_no', 'like', '%' . $requestParams['purchase_no'] . '%');
          }
          if (!empty($requestParams['express'])) {
               $res->where('express', 'like', '%' . $requestParams['express'] . '%');
          }
          $query = $res->order($order)->paginate($limit);
          foreach ($query as &$value) {
               $value['admin_text'] = Db::name('admin')->where('id', $value['admin_id'])->value('username');
               //查询ba_wms_purchase_order_detail表 用采购单号 查询 abnormal 为1的数据
               $value['abnormal'] = Detail::where('order_product_no', $value['purchase_no'])->where('abnormal', 1)->count();
          }
          $this->success('', [
               'list' => $query->items(),
               'total' => $query->total(),
          ]);
     }

     //采购详情
     public function detail(): void
     {
          $id = $this->request->param('id');
          $order = $this->model->with('detail')->find($id);
          if (!$order) {
               $this->error('采购订单不存在');
          }
          $platformData = PurchaseService::platform($order['platform']);
          $db = $platformData['db'] ?? Db::connect('mysql1');
          $order = $order->toArray();
          $xqNums = $db->name('storage_xq_log')->where('status', 0)->group('xq_id')->column('sum(num)', 'xq_id');
          foreach ($order['detail'] as &$value) {
               $value['thumb'] = $value['thumb'] ?? '';
               $value['xq_num'] = $xqNums[$value['xq_id']];
               $value['detail_id'] = $value['id'] ?? '';
               $value['id'] = $value['demand_sku_id'] ?? '';
               $value['title'] = $value['product_title'] ?? '';
               $value['skus'] = [$value];
          }
          $this->success('', $order);
     }

     //采购异常
     public function abnormal_detail(): void
     {
          $id = $this->request->param('id');
          $order = $this->model->with(['detail' => function ($query) {
               $query->where('abnormal', '>=', 1);
          }])->find($id);
          if (!$order) {
               $this->error('采购订单不存在');
          }
          $platformData = PurchaseService::platform($order['platform']);
          $db = $platformData['db'] ?? Db::connect('mysql1');
          $order = $order->toArray();
          $xqNums = $db->name('storage_xq_log')->where('status', 0)->group('xq_id')->column('sum(num)', 'xq_id');
          foreach ($order['detail'] as &$value) {
               $value['thumb'] = $value['thumb'] ?? '';
               $value['xq_num'] = $xqNums[$value['xq_id']];
               $value['detail_id'] = $value['id'] ?? '';
               $value['id'] = $value['demand_sku_id'] ?? '';
               $value['title'] = $value['product_title'] ?? '';
               $value['skus'] = [$value];
          }
          $this->success('', $order);
     }

     //采购异常处理
     public function abnormal_status(): void
     {
          $params = $this->request->param();
          if ($params['status'] == '1') {
               $res = Detail::where('id', $params['id'])->update(['abnormal' => 0]);
          } else {
               $jsonStringDecoded = html_entity_decode($params['detail_json'], ENT_QUOTES, 'UTF-8');
               $detail_json = json_decode($jsonStringDecoded, true);
               //采购订单详情
               $platformData = PurchaseService::platform($params['platform']);
               $db = $platformData['db'] ?? Db::connect('mysql1');


               foreach ($detail_json as $value) {
                    foreach ($value['sku_list'] as $v) {
                         $abnormal = 0;
                         if ($v['plan_quantity'] < $v['actual_quantity']) {
                              $this->error('实际数量不能小于计划数量');
                         }
                         $array = [
                              'plan_quantity' => $v['plan_quantity'],//实际数量
                              'remark' => $v['remark'] ?? '',
                              'abnormal' => $abnormal,
                              'status' => 1,
                              'warehousing_time' => time(),
                         ];
                         $this->model->detail()->where('id', $v['detail_id'])->update($array);
                         //修改其他数据库不存在的采购数据
                         $admin_id = $db->name('admins')->where(['phone' => $this->auth->mobile])->value('id');
                         $db->name('storage_buy')->where('uuid', $v['uuid'])->update([
                              'status' => 2,
                              'end_time' => date('Y-m-d H:i:s', time()),
                              'admin_id2' => $admin_id,
                              'num' => $v['plan_quantity']
                         ]);

                         //修改库存
                         $db->name('storage_xq')->where('id', $v['xq_id'])->update([
                              'stock' => Db::raw('stock+' . $v['plan_quantity']),
                         ]);
                    }
               }

          }
          $this->success(__('Update successful'));
     }


     /**
      * 添加
      */
     public function add(): void
     {
          if ($this->request->isPost()) {
               $data = $this->request->post();
               if (!$data) {
                    $this->error(__('Parameter %s can not be empty', ['']));
               }
               if (!$data['platform']) {
                    $this->error(__('平台ID不能为空', ['']));
               }
               $data = $this->excludeFields($data);
               if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $data[$this->dataLimitField] = $this->auth->id;
               }
               $jsonStringDecoded = html_entity_decode($data['detail_json'], ENT_QUOTES, 'UTF-8');
               $result = false;
               $this->model->startTrans();
               try {
//                    // 模型验证
//                    if ($this->modelValidate) {
//                         $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//                         if (class_exists($validate)) {
//                              $validate = new $validate;
//                              if ($this->modelSceneValidate) $validate->scene('add');
//                              $validate->check($data);
//                         }
//                    }
                    //生成32位雪花ID
                    $data['purchase_no'] = SnowFlake::generateParticle();
                    $result = $this->model->save($data);
                    $detail_json = json_decode($jsonStringDecoded, true);
                    $platformData = PurchaseService::platform($data['platform']);
                    $db = $platformData['db'] ?? Db::connect('mysql1');
                    foreach ($detail_json as $value) {
                         $array = [];
                         foreach ($value['sku_list'] as $v) {
                              $uuid = uniqid() . time();
                              $array[] = [
                                   'demand_sku_id' => $v['demand_sku_id'],
                                   'platform' => $data['platform'],
                                   'xq_id' => $v['xq_id'],
                                   'uuid' => $uuid,
                                   'product_id' => $value['product_id'],
                                   'order_product_no' => $data['purchase_no'],
                                   'actual_quantity' => $v['actual_quantity'],
                                   'price' => $v['price'],
                                   'remark' => $v['remark'] ?? '',
                                   'product_title' => $value['product_title'],
                                   'thumb' => $value['thumb'],
                                   'money_price' => $v['price'] * $v['actual_quantity'],
                                   'admin_id' => $data['admin_id'],
                                   'total_price' => $v['price'] * $v['actual_quantity'],
                              ];
                              $admin_id = $db->name('admins')->where(['phone' => $this->auth->mobile])->value('id');
                              $db->name('storage_buy')->insert([
                                   'uuid' => $uuid,
                                   'title' => $value['product_title'],
                                   'num' => $v['actual_quantity'],
                                   'money_price' => $v['price'] * $v['actual_quantity'],
                                   'product_price' => $v['price'],
                                   'product_total_price' => $v['price'] * $v['actual_quantity'],
                                   'image' => $value['thumb'],
                                   'status' => 1,
                                   'created_at' => date('Y-m-d H:i:s'),
                                   'admin_id' => $admin_id,
                                   'xq_id' => $v['xq_id'],
                              ]);
                         }
                         $this->model->detail()->saveAll($array);

                    }
                    $this->model->commit();
               } catch (Throwable $e) {
                    $this->model->rollback();
                    $this->error($e->getMessage());
               }
               if ($result !== false) {
                    $this->success(__('Added successfully'));
               } else {
                    $this->error(__('No rows were added'));
               }
          }

          $this->error(__('Parameter error'));
     }

     /**
      * 编辑
      * @throws Throwable
      */
     public function edit(): void
     {
          $pk = $this->model->getPk();
          $id = $this->request->param($pk);
          $row = $this->model->find($id);
          if (!$row) {
               $this->error(__('Record not found'));
          }

          $dataLimitAdminIds = $this->getDataLimitAdminIds();
          if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
               $this->error(__('You have no permission'));
          }

          if ($this->request->isPost()) {
               $data = $this->request->post();
               if (!$data) {
                    $this->error(__('Parameter %s can not be empty', ['']));
               }
               if (!$data['platform']) {
                    $this->error(__('平台ID不能为空', ['']));
               }
               $jsonStringDecoded = html_entity_decode($data['detail_json'], ENT_QUOTES, 'UTF-8');
               $data = $this->excludeFields($data);
               $result = false;
               $this->model->startTrans();
//               try {
               // 模型验证
               if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                         $validate = new $validate;
                         if ($this->modelSceneValidate) $validate->scene('edit');
                         $data[$pk] = $row[$pk];
                         $validate->check($data);
                    }
               }
               //修改采购订单
               $result = $row->save($data);
               $arr = [];
               //采购订单详情
               $detail_json = json_decode($jsonStringDecoded, true);
               $ids = $this->model->detail()->where('order_product_no', $data['order_product_no'])->column('id');
               $platformData = PurchaseService::platform($data['platform']);
               $db = $platformData['db'] ?? Db::connect('mysql1');
               foreach ($detail_json as $value) {
                    foreach ($value['sku_list'] as $v) {
                         $array = [
                              'demand_sku_id' => $v['demand_sku_id'],
                              'platform' => $data['platform'],
                              'xq_id' => $v['xq_id'],
                              'product_id' => $value['product_id'],
                              'actual_quantity' => $v['actual_quantity'],
                              'price' => $v['price'],
                              'remark' => $v['remark'] ?? '',
                              'product_title' => $value['product_title'],
                              'thumb' => $value['thumb'],
                              'money_price' => $value['money_price'],
                              'admin_id' => $data['admin_id'],
                              'total_price' => $v['price'] * $v['actual_quantity'],
                         ];
                         //判断是否存在采购详情
                         if (empty($v['detail_id'])) {
                              $array['order_product_no'] = $data['order_product_no'];
                              $array['uuid'] = uniqid() . time();
                              $res = $this->model->detail()->save($array);
                              $arr[] = $res['id'];
                              if ($res) {
                                   $admin_id = $db->name('admins')->where(['phone' => $this->auth->mobile])->value('id');
                                   $db->name('storage_buy')->insert([
                                        'uuid' => $array['uuid'],
                                        'title' => $value['product_title'],
                                        'num' => $v['actual_quantity'],
                                        'money_price' => $v['price'] * $v['actual_quantity'],
                                        'product_price' => $v['price'],
                                        'product_total_price' => $v['price'] * $v['actual_quantity'],
                                        'image' => $value['thumb'],
                                        'status' => 1,
                                        'created_at' => date('Y-m-d H:i:s'),
                                        'admin_id' => $admin_id,
                                        'xq_id' => $v['xq_id'],
                                   ]);
                              }
                         } else if (in_array($v['detail_id'], $ids)) {
                              $arr[] = $v['detail_id'];
                              $this->model->detail()->where('id', $v['detail_id'])->update($array);
                              //修改其他数据库不存在的采购数据
                              $db->name('storage_buy')->where('uuid', $v['uuid'])->update([
                                   'num' => $v['actual_quantity'],
                                   'product_price' => $v['price'],
                                   'money_price' => $v['price'] * $v['actual_quantity'],
                                   'product_total_price' => $v['price'] * $v['actual_quantity'],
                              ]);
                         }
                    }
               }
               //删除不存在的采购详情
               $delete_platform = $this->model->detail()->where('order_product_no', $data['order_product_no'])->whereNotIn('id', $arr)->column('uuid');
               $this->model->detail()->where('order_product_no', $data['order_product_no'])->whereNotIn('id', $arr)->delete();
               //删除其他数据库不存在的采购数据
               foreach ($delete_platform as $value) {
                    $db = Db::connect('mysql1');
                    $db->name('storage_buy')->where('uuid', $value)->delete();
               }

               $this->model->commit();
//               } catch
//               (Throwable $e) {
//                    $this->model->rollback();
//                    $this->error($e->getMessage());
//               }
//               if ($result !== false) {
//                    $this->success(__('Update successful'));
//               } else {
//                    $this->error(__('No rows updated'));
//               }
          }

          $this->success('', [
               'row' => $row
          ]);
     }


     /**
      * 入库
      * @throws Throwable
      */
     public function storage(): void
     {
          $pk = $this->model->getPk();
          $id = $this->request->param($pk);
          $row = $this->model->find($id);
          if (!$row) {
               $this->error(__('Record not found'));
          }

          $dataLimitAdminIds = $this->getDataLimitAdminIds();
          if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
               $this->error(__('You have no permission'));
          }

          if ($this->request->isPost()) {
               $data = $this->request->post();
               if (!$data) {
                    $this->error(__('Parameter %s can not be empty', ['']));
               }
               if (!$data['platform']) {
                    $this->error(__('平台ID不能为空', ['']));
               }
               $jsonStringDecoded = html_entity_decode($data['detail_json'], ENT_QUOTES, 'UTF-8');
               $data = $this->excludeFields($data);
               $result = false;
               $this->model->startTrans();
               try {
                    // 模型验证
//                    if ($this->modelValidate) {
//                         $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
//                         if (class_exists($validate)) {
//                              $validate = new $validate;
//                              if ($this->modelSceneValidate) $validate->scene('edit');
//                              $data[$pk] = $row[$pk];
//                              $validate->check($data);
//                         }
//                    }
                    //修改采购订单
                    $result = $row->save(['status' => 1, 'warehouse_shelf_id' => $data['warehouse_shelf_id'], 'warehousing_time' => time(), 'warehous_id' => $this->auth->id]);
                    //采购订单详情
                    $detail_json = json_decode($jsonStringDecoded, true);
                    $platformData = PurchaseService::platform($data['platform']);
                    $db = $platformData['db'] ?? Db::connect('mysql1');
                    foreach ($detail_json as $value) {
                         foreach ($value['sku_list'] as $v) {
                              $abnormal = 0;
                              if ($v['plan_quantity'] < $v['actual_quantity']) {
                                   $abnormal += 1;
                              }
                              $array = [
                                   'plan_quantity' => $v['plan_quantity'],//实际数量
                                   'remark' => $v['remark'] ?? '',
                                   'abnormal' => $abnormal,
                                   'status' => 1,
                                   'warehousing_time' => time(),
                              ];
                              $this->model->detail()->where('id', $v['detail_id'])->update($array);
                              //修改其他数据库不存在的采购数据
                              $admin_id = $db->name('admins')->where(['phone' => $this->auth->mobile])->value('id');
                              $db->name('storage_buy')->where('uuid', $v['uuid'])->update([
                                   'status' => 2,
                                   'end_time' => date('Y-m-d H:i:s', time()),
                                   'admin_id2' => $admin_id,
                                   'num' => $v['plan_quantity']
                              ]);
                              //修改库存
                              $db->name('storage_xq')->where('id', $v['xq_id'])->update([
                                   'stock' => Db::raw('stock+' . $v['plan_quantity']),
                              ]);
                         }
                    }
                    $this->model->commit();
               } catch
               (Throwable $e) {
                    $this->model->rollback();
                    $this->error($e->getMessage());
               }
               if ($result !== false) {
                    $this->success(__('Update successful'));
               } else {
                    $this->error(__('No rows updated'));
               }
          }

          $this->success('', ['row' => $row]);
     }

     //超可梦商品数据写入
     public function superDream(): void
     {
          $data = $this->request->post();
          if (!$data) {
               $this->error(__('Parameter %s can not be empty', ['']));
          }
          $platformData = PurchaseService::platform($data['platform']);
          $db = $platformData['db'] ?? Db::connect('mysql1');
          $res = $db->name('storage_xq')->where('id', $data['xq_id'])->find();
          if (!$res) {
               $this->error('商品不存在');
          }

     }

}
